#include "types.h"
#include "x86.h"
#include "traps.h"
#include "defs.h"
#include "spinlock.h"

static struct spinlock mouse_lock;

static int state = 0;
static int left_down = 0;
static int right_down = 0;
static int x_sign = 0;
static int y_sign = 0;
static int x_overflow = 0;
static int y_overflow = 0;

void
mouseinit()
{
    outb( 0x64 , 0xa8 );
    outb( 0x64 , 0xd4 );
    outb( 0x60 , 0xf4 );
    outb( 0x64 , 0x60 );
    outb( 0x60 , 0x47 );
    initlock(&mouse_lock,"mouse");
    picenable(IRQ_MOUS);
    ioapicenable(IRQ_MOUS, 0);
}

void
mouseintr(uint tick)
{
	acquire(&mouse_lock);
	uchar ch;
	//ch = inb(0x64);
	//if(ch % 2 == 0 || (ch & 0x20) == 0)
	//	return;

	ch = inb(0x60);

	if(state == 1)
	{
		left_down = (ch & 0x01) ? 1 : 0;
		right_down = (ch & 0x02) ? 1 : 0;
		x_sign = (ch & 0x08) ? 1 : 0;
		y_sign = (ch & 0x10) ? 1 : 0;
		x_overflow = (ch & 0x40) ? 1 : 0;
		y_overflow = (ch & 0x80) ? 1 : 0;
		state = 2;
		release(&mouse_lock);
		cprintf("state1\n");
		return;
	}
	else if(state == 2)
	{
		state = 3;
		release(&mouse_lock);
		cprintf("state2\n");
		return;
	}
	else if(state == 3)
	{
		state = 1;
		release(&mouse_lock);
		cprintf("state3\n");
	}
	else
	{
		state = 1;
		release(&mouse_lock);
		return;
	}

	int event = 0;
	if(left_down == 1)
	{
		cprintf("left_down\n");
		event = 1;
	}
	if(right_down == 1)
	{
		cprintf("right_down\n");
		event = 2;
	}
	mouse_response(event);
}